package com.example.filter;

import com.example.exception.CustomTokenException;
import com.example.redis.RedisCache;
import com.example.redis.RedisKey;
import com.example.security.LoginUser;
import com.example.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 *  OncePerRequestFilter : 请求只会经过这个过滤器一次
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        // 获取 token
        String token = request.getHeader("token");

        if (!StringUtils.hasLength(token)) {
            // token 为空, 放行
            filterChain.doFilter(request, response);
            return;
        }

        // 解析 token
        String userid;
        String jwtId;
        try {
            Claims claims = JwtUtil.parseJWT(token);

            // 获取用户id
            userid = claims.get("userId").toString();

            // 从 jwt 获取 jwtId
            jwtId = claims.get("jwtId").toString();

        } catch (Exception e) {
            throw new CustomTokenException();
        }

        // 从 redis 中获取用户信息
        String redisKey = RedisKey.userKey + userid;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);

        if(Objects.isNull(loginUser) || !loginUser.getJwtId().equals(jwtId)){
            throw new CustomTokenException();
        }


        // 存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken =
                // 必须使用三个参数的构造方法 -> 标志用户已认证
                new UsernamePasswordAuthenticationToken(loginUser,null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 放行
        filterChain.doFilter(request, response);
    }
}